package com.hksj.Intelligentmanagement.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hksj.Intelligentmanagement.common.Result;
import com.hksj.Intelligentmanagement.dto.MqttAuthDTO;
import com.hksj.Intelligentmanagement.entity.MqttAuthEntity;
import com.hksj.Intelligentmanagement.mapper.MqttAuthMapper;
import com.hksj.Intelligentmanagement.vo.MqttAuthVo;
import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @Author zengke
 * @ClassName MqttAuthService
 * @Date 2023/3/22 17:28
 * @Version 1.0
 * @Description TODO
 */

/**
 * mqtt认证业务
 */
@Service
public class MqttAuthService {
    //日志打印
    private static final Logger log = LoggerFactory.getLogger(MqttAuthService.class);

    @Autowired
    private MqttAuthMapper mqttAuthMapper;

    @Autowired
    private Mapper mapper;

    //创建mqtt认证参数
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Result createMqttAuth(MqttAuthDTO mqttAuthDTO) {

        //通过clientId和username查询在数据库中是否存在---emqx不支持完全相同的两个客户端推送数据
        LambdaQueryWrapper<MqttAuthEntity> wrapper = new QueryWrapper<MqttAuthEntity>().lambda()
                .eq(MqttAuthEntity::getClientId, mqttAuthDTO.getClientId())
                .eq(MqttAuthEntity::getUsername, mqttAuthDTO.getUsername());

        MqttAuthEntity mqttAuthEntity = mqttAuthMapper.selectOne(wrapper);
        if (!Objects.isNull(mqttAuthEntity)) {
            //不为空
            return Result.error("mqtt参数创建失败,请勿已有的客户端参数");
        }

        //创建
        //先将mqttAuthDTO转为mqttEntity
        mqttAuthEntity = mapper.map(mqttAuthDTO, MqttAuthEntity.class);

        //在表中创建一条记录
        mqttAuthMapper.insert(mqttAuthEntity);
        return Result.ok("创建mqtt认证参数成功");
    }

    //删除mqtt认证参数
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Result deleteMqttAuth(String id) {

        //通过id查询该记录在数据库中是否存在
        MqttAuthEntity mqttAuthEntity = mqttAuthMapper.selectById(id);

        if (Objects.isNull(mqttAuthEntity)) {
            //不存在
            return Result.error("输入的id有误,删除mqtt认证参数失败");
        }

        //删除
        mqttAuthMapper.deleteById(id);
        return Result.ok("删除mqtt认证参数成功");
    }

    //修改mqtt认证参数
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Result updateMqttAuth(MqttAuthDTO mqttAuthDTO) {

        //通过id查询该mqtt认证参数的记录是否存在
        MqttAuthEntity mqttAuthEntity = mqttAuthMapper.selectById(mqttAuthDTO.getId());

        if (Objects.isNull(mqttAuthEntity)) {
            //不存在
            return Result.error("输入的id有误,修改参数设置失败");
        }

        //根据clientId、username查询是否存在该记录
        LambdaQueryWrapper<MqttAuthEntity> wrapper = new QueryWrapper<MqttAuthEntity>().lambda()
                .eq(MqttAuthEntity::getClientId, mqttAuthDTO.getClientId())
                .eq(MqttAuthEntity::getUsername, mqttAuthDTO.getUsername());

        mqttAuthEntity = mqttAuthMapper.selectOne(wrapper);

        if (!Objects.isNull(mqttAuthEntity)) {
            return Result.error("该记录已存在,修改失败");
        }

        //更新
        //先将传来的mqttAuthDTO转为mqttAuthEntity
        mqttAuthEntity = mapper.map(mqttAuthDTO, MqttAuthEntity.class);

        //做更新
        mqttAuthMapper.updateById(mqttAuthEntity);
        return Result.ok("更新mqtt认证参数成功");
    }


    //分页动态查询mqtt认证参数列表
    public IPage<MqttAuthVo> queryMqttAuthListByPage(MqttAuthDTO mqttAuthDTO) {

        //创建一个分页实例
        IPage<MqttAuthVo> page = new Page<>(mqttAuthDTO.getPageNum(), mqttAuthDTO.getPageSize());

        //对查询进行分页
        List<MqttAuthVo> mqttAuthVos = mqttAuthMapper.queryMqttAuthListByPage(page, mqttAuthDTO);

        //保存分页记录
        page.setRecords(mqttAuthVos);

        //返回分页
        return page;
    }

    //设备认证
    public ResponseEntity<Object> auth(String clientId, String username, String password) {
        if(username.equals("admin")){
            LambdaQueryWrapper<MqttAuthEntity> wrapper = new LambdaQueryWrapper<MqttAuthEntity>()
                    .eq(MqttAuthEntity::getUsername,username);

            MqttAuthEntity mqttAuthEntity = mqttAuthMapper.selectOne(wrapper);

            if (!password.equals(mqttAuthEntity.getPassword())) {
                //不一致,认证失败
                return new ResponseEntity<>("mqtt连接密码有误,请重新输入", HttpStatus.UNAUTHORIZED);
            }
            return new ResponseEntity<>("认证成功", HttpStatus.OK);
        }

        //1.通过clientId,username查询数据库中是否存在该设备
        LambdaQueryWrapper<MqttAuthEntity> wrapper = new QueryWrapper<MqttAuthEntity>().lambda()
                .eq(MqttAuthEntity::getClientId,clientId)
                .eq(MqttAuthEntity::getUsername,username);
        MqttAuthEntity mqttAuthEntity = mqttAuthMapper.selectOne(wrapper);

        if (Objects.isNull(mqttAuthEntity)) {
            //数据库中不存在,认证失败
            return new ResponseEntity<>("mqtt连接参数不存在,认证失败", HttpStatus.UNAUTHORIZED);
        }

        //2.判断查询出来的设备password是否和设备密钥一致
        if (!password.equals(mqttAuthEntity.getPassword())) {
            //不一致,认证失败
            return new ResponseEntity<>("mqtt连接密码有误,请重新输入", HttpStatus.UNAUTHORIZED);
        }
        //3.设备的clientId,username,password跟数据库记录的相同,认证成功
        return new ResponseEntity<>("认证成功", HttpStatus.OK);
    }


    public ResponseEntity<Object> superuser(String clientid, String username) {

        log.info("emqx查询用户是否是超级用户,clientid={},username={}", clientid, username);

        if (clientid.contains("admin") || username.contains("admin")) {
            log.info("用户{}是超级用户", username);
            return new ResponseEntity<>(HttpStatus.OK);
        } else {
            log.info("用户{}不是超级用户", username);
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
    }

    public ResponseEntity<Object> acl(int access, String username, String clientid, String ipaddr, String topic, String mountpoint) {
        log.info("emqx发起客户端操作授权查询请求,access={},username={},clientid={},ipaddr={},topic={},mountpoint={}",
                access, username, clientid, ipaddr, topic, mountpoint);

        return new ResponseEntity<>(HttpStatus.OK);
    }
}
